<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">






  
  
    
      
    
    
      
    
  <script src="https://cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
  <link href="https://cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-flash.min.css" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















  

<link href="https://cdn.bootcss.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="react-lazy-load粗读近来没什么特别要做的事，下班回来的空闲时间也比较多，所以抽空看看懒加载是怎么实现的，特别是看了下 react-lazy-load 的库的实现。 懒加载这里懒加载场景不是路由分割打包那种，而是单个页面中有一个很长的列表，列表中的图片进行懒加载的效果。 在 jquery 时代，这种列表图片懒加载效果就已经有了，那么我们想一想这种在滚动的时候才去加载图片等资源的方式该如">
<meta name="keywords" content="react,源码,懒加载">
<meta property="og:type" content="article">
<meta property="og:title" content="懒加载">
<meta property="og:url" content="http://yoursite.com/2018/08/14/懒加载/index.html">
<meta property="og:site_name" content="三月的米店">
<meta property="og:description" content="react-lazy-load粗读近来没什么特别要做的事，下班回来的空闲时间也比较多，所以抽空看看懒加载是怎么实现的，特别是看了下 react-lazy-load 的库的实现。 懒加载这里懒加载场景不是路由分割打包那种，而是单个页面中有一个很长的列表，列表中的图片进行懒加载的效果。 在 jquery 时代，这种列表图片懒加载效果就已经有了，那么我们想一想这种在滚动的时候才去加载图片等资源的方式该如">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/2018/08/14/懒加载/433381594.jpg">
<meta property="og:updated_time" content="2018-11-29T02:09:38.120Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="懒加载">
<meta name="twitter:description" content="react-lazy-load粗读近来没什么特别要做的事，下班回来的空闲时间也比较多，所以抽空看看懒加载是怎么实现的，特别是看了下 react-lazy-load 的库的实现。 懒加载这里懒加载场景不是路由分割打包那种，而是单个页面中有一个很长的列表，列表中的图片进行懒加载的效果。 在 jquery 时代，这种列表图片懒加载效果就已经有了，那么我们想一想这种在滚动的时候才去加载图片等资源的方式该如">
<meta name="twitter:image" content="http://yoursite.com/2018/08/14/懒加载/433381594.jpg">






  <link rel="canonical" href="http://yoursite.com/2018/08/14/懒加载/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>懒加载 | 三月的米店</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">三月的米店</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">今儿不吃饭</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/08/14/懒加载/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Mark Lee">
      <meta itemprop="description" content="折腾小久的博客,在 2018-08-01 终于基本成型啦，以后就常驻啦">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="三月的米店">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">懒加载
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-08-14 14:28:16" itemprop="dateCreated datePublished" datetime="2018-08-14T14:28:16+08:00">2018-08-14</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2018-11-29 10:09:38" itemprop="dateModified" datetime="2018-11-29T10:09:38+08:00">2018-11-29</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/前端/" itemprop="url" rel="index"><span itemprop="name">前端</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="react-lazy-load粗读"><a href="#react-lazy-load粗读" class="headerlink" title="react-lazy-load粗读"></a>react-lazy-load粗读</h1><p>近来没什么特别要做的事，下班回来的空闲时间也比较多，所以抽空看看懒加载是怎么实现的，特别是看了下 <code>react-lazy-load</code> 的库的实现。</p>
<h2 id="懒加载"><a href="#懒加载" class="headerlink" title="懒加载"></a>懒加载</h2><p>这里懒加载场景不是路由分割打包那种，而是单个页面中有一个很长的列表，列表中的图片进行懒加载的效果。</p>
<p>在 <code>jquery</code> 时代，这种列表图片懒加载效果就已经有了，那么我们想一想这种在滚动的时候才去加载图片等资源的方式该如何去实现呢？</p>
<h2 id="大致原理"><a href="#大致原理" class="headerlink" title="大致原理"></a>大致原理</h2><p>浏览器解析 <code>html</code> 的时候，在遇到 <code>img</code> 标签以及发现 <code>src</code> 属性的时候，浏览器就会去发请求拿图片去了。这里就是切入点，根据这种现象，做下面几件事：</p>
<ol>
<li>把列表中所有的图片的 <code>img</code> 标签的 <code>src</code> 设为空</li>
<li>把真实的图片路径存成一个 <code>dom</code> 属性，打个比方: <code>&lt;img data-src=&#39;/xxxxx.jpg&#39; /&gt;</code></li>
<li>写一个检测列表某一项是否是可见状态</li>
<li>全局滚动事件做一个监听，检测当前列表的项是否是可见的，如果可见则给 <code>img</code> 标签上存着真实图片路径赋值给 <code>src</code> 属性</li>
</ol>
<h2 id="react-lazy-load"><a href="#react-lazy-load" class="headerlink" title="react-lazy-load"></a>react-lazy-load</h2><p>知道懒加载的大概原理，来看一下 <code>react-lazy-load</code> 是怎么做的。</p>
<p>大体看了下 <code>react-lazy-load</code> 的实现的总体思路就更加简单了，本质上就是让需要懒加载的组件包含在这个包提供的 <code>LazyLoad</code> 组件中，不渲染这个组件，然后去监听这个 <code>LazyLoad</code> 组件是否已经是可见了，如果是可见了那么就去强制渲染包含在 <code>LazyLoad</code> 组件内部需要懒加载的组件了。</p>
<p>这种方式相较于手动去控制 <code>img</code> 标签来的实在是太方便了，完全以组件为单位，对组件进行懒加载。这样的话，完全就不需要感知组件内部的逻辑和渲染逻辑，无论这个需要懒加载的组件内部是有几个 <code>img</code> 标签，也完全不用去手动操控 <code>src</code> 属性的赋值。</p>
<h3 id="react-lazy-load-之-render"><a href="#react-lazy-load-之-render" class="headerlink" title="react-lazy-load 之 render"></a>react-lazy-load 之 render</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LazyLoad</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span></span>&#123;</span><br><span class="line">    <span class="keyword">constructor</span>(props) &#123;</span><br><span class="line">        <span class="keyword">super</span>(props)</span><br><span class="line">        <span class="keyword">this</span>.visible = <span class="literal">false</span></span><br><span class="line">    &#125;</span><br><span class="line">    componentDidMount() &#123;</span><br><span class="line">        <span class="comment">// 主要是监听事件</span></span><br><span class="line">        <span class="comment">// 省略此处代码</span></span><br><span class="line">    &#125;</span><br><span class="line">    shouldComponentUpdate() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.visible</span><br><span class="line">    &#125;</span><br><span class="line">    componentWillUnmount() &#123;</span><br><span class="line">        <span class="comment">// 主要是移除监听事件</span></span><br><span class="line">        <span class="comment">// 省略</span></span><br><span class="line">    &#125;</span><br><span class="line">    render () &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.visible</span><br><span class="line">                ? <span class="keyword">this</span>.props.children</span><br><span class="line">                : <span class="keyword">this</span>.props.placeholder</span><br><span class="line">                    ? <span class="keyword">this</span>.props.placeholder</span><br><span class="line">                    : <span class="xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">&#123;&#123;</span> <span class="attr">height:</span> <span class="attr">this.props.height</span> &#125;&#125; <span class="attr">className</span>=<span class="string">"lazyload-placeholder"</span> /&gt;</span></span></span><br><span class="line"><span class="xml">    &#125;</span></span><br><span class="line"><span class="xml">&#125;</span></span><br></pre></td></tr></table></figure>
<p>从 <code>render</code> 函数能够看出来，依据当前 <code>visible</code> 的值来确定是否渲染 <code>this.props.children</code>，如果为 <code>false</code> 则去渲染节点的占位符。如果外部传入一个占位节点，就用这个传入的占位节点，否则就用默认的占位符去占位。注意到：<code>shouldComponentUpdate</code> 依据 <code>this.visible</code> 的值去判断是否更新组件。剩下的，该去看看如何监听事件以及修改 <code>this.visible</code>、强制重新渲染组件的。</p>
<h3 id="react-lazy-load-之-componentDidMount"><a href="#react-lazy-load-之-componentDidMount" class="headerlink" title="react-lazy-load 之 componentDidMount"></a>react-lazy-load 之 componentDidMount</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">componentDidMount() &#123;</span><br><span class="line">  <span class="comment">// It's unlikely to change delay type on the fly, this is mainly</span></span><br><span class="line">  <span class="comment">// designed for tests</span></span><br><span class="line">  <span class="keyword">const</span> needResetFinalLazyLoadHandler = (<span class="keyword">this</span>.props.debounce !== <span class="literal">undefined</span> &amp;&amp; delayType === <span class="string">'throttle'</span>)</span><br><span class="line">    || (delayType === <span class="string">'debounce'</span> &amp;&amp; <span class="keyword">this</span>.props.debounce === <span class="literal">undefined</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (needResetFinalLazyLoadHandler) &#123;</span><br><span class="line">    off(<span class="built_in">window</span>, <span class="string">'scroll'</span>, finalLazyLoadHandler, passiveEvent);</span><br><span class="line">    off(<span class="built_in">window</span>, <span class="string">'resize'</span>, finalLazyLoadHandler, passiveEvent);</span><br><span class="line">    finalLazyLoadHandler = <span class="literal">null</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (!finalLazyLoadHandler) &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.props.debounce !== <span class="literal">undefined</span>) &#123;</span><br><span class="line">      finalLazyLoadHandler = debounce(lazyLoadHandler, <span class="keyword">typeof</span> <span class="keyword">this</span>.props.debounce === <span class="string">'number'</span> ?</span><br><span class="line">                                                       <span class="keyword">this</span>.props.debounce :</span><br><span class="line">                                                       <span class="number">300</span>);</span><br><span class="line">      delayType = <span class="string">'debounce'</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">this</span>.props.throttle !== <span class="literal">undefined</span>) &#123;</span><br><span class="line">      finalLazyLoadHandler = throttle(lazyLoadHandler, <span class="keyword">typeof</span> <span class="keyword">this</span>.props.throttle === <span class="string">'number'</span> ?</span><br><span class="line">                                                       <span class="keyword">this</span>.props.throttle :</span><br><span class="line">                                                       <span class="number">300</span>);</span><br><span class="line">      delayType = <span class="string">'throttle'</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      finalLazyLoadHandler = lazyLoadHandler;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">this</span>.props.overflow) &#123;</span><br><span class="line">    <span class="keyword">const</span> parent = scrollParent(ReactDom.findDOMNode(<span class="keyword">this</span>));</span><br><span class="line">    <span class="keyword">if</span> (parent &amp;&amp; <span class="keyword">typeof</span> parent.getAttribute === <span class="string">'function'</span>) &#123;</span><br><span class="line">      <span class="keyword">const</span> listenerCount = <span class="number">1</span> + (+parent.getAttribute(LISTEN_FLAG));</span><br><span class="line">      <span class="keyword">if</span> (listenerCount === <span class="number">1</span>) &#123;</span><br><span class="line">        parent.addEventListener(<span class="string">'scroll'</span>, finalLazyLoadHandler, passiveEvent);</span><br><span class="line">      &#125;</span><br><span class="line">      parent.setAttribute(LISTEN_FLAG, listenerCount);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (listeners.length === <span class="number">0</span> || needResetFinalLazyLoadHandler) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; scroll, resize &#125; = <span class="keyword">this</span>.props;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (scroll) &#123;</span><br><span class="line">      on(<span class="built_in">window</span>, <span class="string">'scroll'</span>, finalLazyLoadHandler, passiveEvent);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (resize) &#123;</span><br><span class="line">      on(<span class="built_in">window</span>, <span class="string">'resize'</span>, finalLazyLoadHandler, passiveEvent);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  listeners.push(<span class="keyword">this</span>);</span><br><span class="line">  checkVisible(<span class="keyword">this</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>needResetFinalLazyLoadHandler</code> 先别关注，按他给注释说测试用。 <code>finalLazyLoadHandler</code> 依据外部 <code>debounce</code> 和 <code>throttle</code> 来选择是防抖还是节流还是都不用。根据外部传入的<code>overflow</code> 来确定是否是在某一个节点中 <code>overflow</code> 的下拉框的懒加载还是普通的整个 <code>window</code> 的懒加载。然后就是依据是 <code>scroll</code> 还是 <code>resize</code> 来给 <code>window</code> 增加监听事件 <code>finalLazyLoadHandler</code>。 最后就是把这个组件实例放到了 <code>listeners</code> 这个数组里，然后调用 <code>checkVisible</code> 检查是否可见。</p>
<h3 id="react-lazy-load-之-checkVisible"><a href="#react-lazy-load-之-checkVisible" class="headerlink" title="react-lazy-load 之 checkVisible"></a>react-lazy-load 之 checkVisible</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Detect if element is visible in viewport, if so, set `visible` state to true.</span></span><br><span class="line"><span class="comment"> * If `once` prop is provided true, remove component as listener after checkVisible</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * @param  &#123;React&#125; component   React component that respond to scroll and resize</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> checkVisible = <span class="function"><span class="keyword">function</span> <span class="title">checkVisible</span>(<span class="params">component</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> node = ReactDom.findDOMNode(component);</span><br><span class="line">  <span class="keyword">if</span> (!node) &#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> parent = scrollParent(node);</span><br><span class="line">  <span class="keyword">const</span> isOverflow = component.props.overflow &amp;&amp;</span><br><span class="line">                     parent !== node.ownerDocument &amp;&amp;</span><br><span class="line">                     parent !== <span class="built_in">document</span> &amp;&amp;</span><br><span class="line">                     parent !== <span class="built_in">document</span>.documentElement;</span><br><span class="line">  <span class="keyword">const</span> visible = isOverflow ?</span><br><span class="line">                  checkOverflowVisible(component, parent) :</span><br><span class="line">                  checkNormalVisible(component);</span><br><span class="line">  <span class="keyword">if</span> (visible) &#123;</span><br><span class="line">    <span class="comment">// Avoid extra render if previously is visible</span></span><br><span class="line">    <span class="keyword">if</span> (!component.visible) &#123;</span><br><span class="line">      <span class="keyword">if</span> (component.props.once) &#123;</span><br><span class="line">        pending.push(component);</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      component.visible = <span class="literal">true</span>;</span><br><span class="line">      component.forceUpdate();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!(component.props.once &amp;&amp; component.visible)) &#123;</span><br><span class="line">    component.visible = <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (component.props.unmountIfInvisible) &#123;</span><br><span class="line">      component.forceUpdate();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><code>parent</code> 就是找到这个组件的上层组件的 <code>dom</code> 节点，通过 <code>checkOverflowVisible</code> 和 <code>checkNormalVisible</code>这两个函数拿到该节点是否在可视区域内得到 <code>visible</code>。然后依据 <code>visible</code>的值修改 <code>component</code> 的 <code>visible</code>的值，然后调用组件的 <code>forceUpdate</code> 方法，强制让组件重新渲染。主要到组件的 <code>visible</code> 并不是挂载到 <code>state</code> 上，所以这里不是用 <code>setState</code> 来重新渲染。</p>
<h3 id="react-lazy-load-之-checkNormalVisible"><a href="#react-lazy-load-之-checkNormalVisible" class="headerlink" title="react-lazy-load 之 checkNormalVisible"></a>react-lazy-load 之 checkNormalVisible</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Check if `component` is visible in document</span></span><br><span class="line"><span class="comment"> * @param  &#123;node&#125; component React component</span></span><br><span class="line"><span class="comment"> * @return &#123;bool&#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> checkNormalVisible = <span class="function"><span class="keyword">function</span> <span class="title">checkNormalVisible</span>(<span class="params">component</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> node = ReactDom.findDOMNode(component);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// If this element is hidden by css rules somehow, it's definitely invisible</span></span><br><span class="line">  <span class="keyword">if</span> (!(node.offsetWidth || node.offsetHeight || node.getClientRects().length)) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">let</span> top;</span><br><span class="line">  <span class="keyword">let</span> elementHeight;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    (&#123; top, <span class="attr">height</span>: elementHeight &#125; = node.getBoundingClientRect());</span><br><span class="line">  &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">    (&#123; top, <span class="attr">height</span>: elementHeight &#125; = defaultBoundingClientRect);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> windowInnerHeight = <span class="built_in">window</span>.innerHeight || <span class="built_in">document</span>.documentElement.clientHeight;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> offsets = <span class="built_in">Array</span>.isArray(component.props.offset) ?</span><br><span class="line">                component.props.offset :</span><br><span class="line">                [component.props.offset, component.props.offset]; <span class="comment">// Be compatible with previous API</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (top - offsets[<span class="number">0</span>] &lt;= windowInnerHeight) &amp;&amp;</span><br><span class="line">         (top + elementHeight + offsets[<span class="number">1</span>] &gt;= <span class="number">0</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>主要逻辑就是拿到组件的 <code>dom</code> 节点的 <code>getBoundingClientRect</code> 返回值和 <code>window.innerHeight</code> 进行比较来判断是否是在可视范围内。这里在比较的时候还有个 <code>component.props.offset</code> 也参与了比较，说明设置了 <code>offset</code> 的时候，组件快要出现在可视范围的时候就会去重新渲染组件而不是出现在可视范围内才去重新渲染。</p>
<h3 id="react-lazy-load-之-lazyLoadHandler"><a href="#react-lazy-load-之-lazyLoadHandler" class="headerlink" title="react-lazy-load 之 lazyLoadHandler"></a>react-lazy-load 之 lazyLoadHandler</h3><p><code>lazyLoadHandler</code> 是组件绑定事件时会触发的函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> lazyLoadHandler = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; listeners.length; ++i) &#123;</span><br><span class="line">    <span class="keyword">const</span> listener = listeners[i];</span><br><span class="line">    checkVisible(listener);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// Remove `once` component in listeners</span></span><br><span class="line">  purgePending();</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>每次监听事件执行的时候，都去检查一下组件，如果满足条件就去强制渲染组件。</p>
<h3 id="react-lazy-load-之-componentWillUnmount"><a href="#react-lazy-load-之-componentWillUnmount" class="headerlink" title="react-lazy-load 之 componentWillUnmount"></a>react-lazy-load 之 componentWillUnmount</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">componentWillUnmount() &#123;</span><br><span class="line">   <span class="keyword">if</span> (<span class="keyword">this</span>.props.overflow) &#123;</span><br><span class="line">     <span class="keyword">const</span> parent = scrollParent(ReactDom.findDOMNode(<span class="keyword">this</span>));</span><br><span class="line">     <span class="keyword">if</span> (parent &amp;&amp; <span class="keyword">typeof</span> parent.getAttribute === <span class="string">'function'</span>) &#123;</span><br><span class="line">       <span class="keyword">const</span> listenerCount = (+parent.getAttribute(LISTEN_FLAG)) - <span class="number">1</span>;</span><br><span class="line">       <span class="keyword">if</span> (listenerCount === <span class="number">0</span>) &#123;</span><br><span class="line">         parent.removeEventListener(<span class="string">'scroll'</span>, finalLazyLoadHandler, passiveEvent);</span><br><span class="line">         parent.removeAttribute(LISTEN_FLAG);</span><br><span class="line">       &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">         parent.setAttribute(LISTEN_FLAG, listenerCount);</span><br><span class="line">       &#125;</span><br><span class="line">     &#125;</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">const</span> index = listeners.indexOf(<span class="keyword">this</span>);</span><br><span class="line">   <span class="keyword">if</span> (index !== <span class="number">-1</span>) &#123;</span><br><span class="line">     listeners.splice(index, <span class="number">1</span>);</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">if</span> (listeners.length === <span class="number">0</span>) &#123;</span><br><span class="line">     off(<span class="built_in">window</span>, <span class="string">'resize'</span>, finalLazyLoadHandler, passiveEvent);</span><br><span class="line">     off(<span class="built_in">window</span>, <span class="string">'scroll'</span>, finalLazyLoadHandler, passiveEvent);</span><br><span class="line">   &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>组件卸载的时候，把一些绑定事件解绑一下，细节也不说了。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>抛开 <code>react-lazy-load</code> 一些实现细节，从总体把握整个懒加载的过程，其实懒加载的原理并不难。当时我也看了一下 <code>vue</code> 那边的 <code>vue-lazyLoad</code> 这个库想写一个对比的文章，我以为这个 <code>vue</code> 库的内容会写的和 <code>react-lazy-load</code> 差不多，结果发现 <code>vue-lazyLoad</code> 代码很长而且好像比较复杂，所以也就没看了。</p>
<hr>
<p><img src="/2018/08/14/懒加载/433381594.jpg" alt="Vincent van Gogh – Blossoming Almond Branch in a Glass with a Book"></p>
<blockquote>
<p>Vincent van Gogh – Blossoming Almond Branch in a Glass with a Book 1888</p>
</blockquote>

      
    </div>

    

    
    
    

    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/react/" rel="tag"><i class="fa fa-tag"></i> react</a>
          
            <a href="/tags/源码/" rel="tag"><i class="fa fa-tag"></i> 源码</a>
          
            <a href="/tags/懒加载/" rel="tag"><i class="fa fa-tag"></i> 懒加载</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/03/redux之createStore/" rel="next" title="redux之createStore">
                <i class="fa fa-chevron-left"></i> redux之createStore
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/14/react-motion翻译及学习/" rel="prev" title="react-motion翻译及学习">
                react-motion翻译及学习 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Mark Lee</p>
              <p class="site-description motion-element" itemprop="description">折腾小久的博客,在 2018-08-01 终于基本成型啦，以后就常驻啦</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">26</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">20</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#react-lazy-load粗读"><span class="nav-number">1.</span> <span class="nav-text">react-lazy-load粗读</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#懒加载"><span class="nav-number">1.1.</span> <span class="nav-text">懒加载</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#大致原理"><span class="nav-number">1.2.</span> <span class="nav-text">大致原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#react-lazy-load"><span class="nav-number">1.3.</span> <span class="nav-text">react-lazy-load</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#react-lazy-load-之-render"><span class="nav-number">1.3.1.</span> <span class="nav-text">react-lazy-load 之 render</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#react-lazy-load-之-componentDidMount"><span class="nav-number">1.3.2.</span> <span class="nav-text">react-lazy-load 之 componentDidMount</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#react-lazy-load-之-checkVisible"><span class="nav-number">1.3.3.</span> <span class="nav-text">react-lazy-load 之 checkVisible</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#react-lazy-load-之-checkNormalVisible"><span class="nav-number">1.3.4.</span> <span class="nav-text">react-lazy-load 之 checkNormalVisible</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#react-lazy-load-之-lazyLoadHandler"><span class="nav-number">1.3.5.</span> <span class="nav-text">react-lazy-load 之 lazyLoadHandler</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#react-lazy-load-之-componentWillUnmount"><span class="nav-number">1.3.6.</span> <span class="nav-text">react-lazy-load 之 componentWillUnmount</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">1.4.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Mark Lee</span>

  

  
</div>


  


<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" rel="external nofollow" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" rel="external nofollow" href="https://theme-next.org">NexT.Pisces</a> v6.3.0</div>

-->



        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.3.0"></script>



  



  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
